# 处理消息，调用消息处理器
import traceback

from py.handler import local_email
from py.uitls.Logger import myLogger

_handlers = {}


def add_handler(name, handler):
    if name in _handlers.keys():
        raise Exception("已存在消息处理器：%s" % name)
    else:
        _handlers[name] = handler


# 处理收到的指令
def handler(addr, title, content):
    if title not in _handlers.keys():
        myLogger.warn("不存在消息处理器%s" % title)
    else:
        myLogger.info("邮件处理器：%s", title)
        try:
            title, content, file = _handlers[title].handle(title, content)
            myLogger.info("消息处理完成，回传消息")
            local_email.send_mail(addr, title, content, file)
        except Exception as e:
            myLogger.exception(e)
            local_email.send_mail(addr, "执行指令异常", traceback.format_exc())
